/*
 * @Author: your name
 * @Date: 2021-03-11 15:18:47
 * @LastEditTime: 2021-03-12 15:11:45
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \ui-demo\src\api\request.js
 */
import axios from 'axios' // 引入axios
import { Message } from 'element-ui'
import router from '@/router'
// 设置post请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
axios.defaults.withCredentials = false// 在跨域请求时，不会携带用户凭证；返回的 response 里也会忽略 cookie
axios.defaults.baseURL = '/api'
// axios.withCredentials = true

// 创建axios实例，请求超时时间为300秒
const service = axios.create({
  // baseURL: process.env.BASE_API,
  // withCredentials: true,
  timeout: 300000
})

// 请求发起前拦截
service.interceptors.request.use(async (config) => {
  // 这里可以对接口请求头进行操作 如：config.headers['X-Token'] = token
  console.log('请求拦截', config)

  // 如果请求没有token则默认添加上
  if (localStorage.getItem('access_token')) {
    // 请求头Authorization为空的时候添加token,除了登陆
    if (!config.headers['Authorization'] && !config.url.includes('/app/user/login')) {
      config.headers['Authorization'] = localStorage.getItem('access_token')
    }
  }

  return config
}, (error) => {
  // Do something with request error
  return Promise.reject(error)
})

// 响应拦截（请求返回后拦截）
service.interceptors.response.use(response => {
  const res = response.data

  if (res.code !== 0) {
    Message({
      message: res.msg || '系统异常',
      type: 'error',
      duration: 3 * 1000
    })
    // 授权失败或者过期直接返回登陆界面
    if (res.code === 401) {
      router.push({path: '/'})
    }
    return Promise.reject(res.msg || 'error')
  } else {
    return res
  }
}, error => {
  Message({
    message: '系统异常',
    type: 'error',
    duration: 3 * 1000
  })
  console.log('catch', error)

  return Promise.reject(error)
})

export default service
